package p.lodz.pl.poid.zad2;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.fxml.FXMLLoader;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import p.lodz.pl.poid.zad2.controller.Controllable;

/**
 *
 * @author janiu
 */
public class Loader extends FXMLLoader {

    private final String ui; 
    private Scene scene;
    private AnchorPane root;
    
    public Loader(String ui, AnchorPane anchorPane) throws IOException {
        this.ui = ui;
        initLoader(anchorPane.getClass());
        initRoot(anchorPane);
    }
    
    public Loader(String ui, Class location) { 
        this.ui = ui;
        initLoader(location);
        initRoot();
        initController();
    }
    
    private void initLoader(Class location) {
        this.setBuilderFactory(new JavaFXBuilderFactory());
        this.setLocation(location.getResource(ui));
    }
    
    private void initRoot() {       
        try {
            root = (AnchorPane) this.load();
            scene = new Scene(root);
        } catch (IOException ex) {
            Logger.getLogger(Loader.class.getName()).log(Level.SEVERE, null, ex);
        }         
    }
    
    private void initRoot(AnchorPane anchorPane) {
        try {
            this.setRoot(anchorPane);
            this.load();
        } catch (IOException ex) {
            Logger.getLogger(Loader.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void initController() {        
        Controllable mainController = this.getController();
        mainController.setScene(scene);        
    }

    @Override
    public AnchorPane getRoot() {
        return root;
    }
    
    public Scene getScene() {
        return scene;
    }
}
